package com.durl.simple;

import org.nutz.lang.Lang;

public class UrlWeaver {

	private static boolean init;

	// 26进制
	private static char[] chars = new char[26];
	private static int point;
	private static int start;

	public static void initResources(UrlEntity en) {
		if (en == null) {
			point = chars.length - 1;
			start = point;
		} else {
			String url = en.getShorturl();
			char[] urls = url.toCharArray();
			for (int i = 0; i < urls.length; i++) {
				chars[i] = urls[i];
			}
			start = chars.length - url.length();
		}
		init = true;
	}

	public static synchronized String next() {
		if (!init)
			throw Lang.makeThrow("Did not init UrlWeaver!");
		return addOneStep();
	}

	private static String addOneStep() {
		char c = chars[point];
		if (c == 0) {
			chars[point] = 'a';
		} else if (c == 'z') {
			chars[point] = 'a';
			if (--point < start)
				start--;
			return addOneStep();
		} else {
			chars[point]++;
		}
		point = chars.length - 1;
		StringBuilder sb = new StringBuilder();
		for (int i = start; i <= point; i++) {
			sb.append(chars[i]);
		}
		return sb.toString();
	}

}
